package com.mydesign.demo.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * HTTP请求工具类，用于处理HTTP请求
 *
 * @author GZF
 *
 */
public class HttpUtil {

    /**
     * 连接超时
     */
    private static int TIME_OUT = 5000;

    /**
     * 读取数据超时
     */
    private static int READ_OUT = 10000;

    /**
     * 请求编码
     */
    private static String ENCODING = "UTF-8";

    private static Logger logger = Logger.getLogger(HttpUtil.class);

    private static final CloseableHttpClient httpclient = HttpClients.createDefault();
    // private static Logger logger = Logger.getLogger(HttpUtil.class);
    /**
     *
     * @Title: HttpRecevie @author: LYQ @Description:
     * 根据当前的请求对象，获得请求里的数据流 @Createtime: Sep 17, 2012 @param @param request
     * 当前请求的对象 @param @return 设定文件 @return String 返回类型 @throws
     */
    public static String HttpRecevie(HttpServletRequest request) {
        String re = null;
        try {
            // 读取请求内容
            BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            re = sb.toString();
            /***
             * 注：以下代码是在action中必须写的。否则返回的数据可能有乱码
             */
            // response.setCharacterEncoding("UTF-8");
            // response.setContentType("text/html;charset=UTF-8");
            // PrintWriter writer = response.getWriter();
            // String a = "你好";
            // writer.write(("{\"result\":" + a + "}"));
        } catch (IOException e) {
            logger.error("HttpClientUtils:根据请求对象获取改请求对象里的内容出错:" + e.getMessage());
            return null;
        }
        return re;
    }

    /**
     * @Title: HttpClientPost @author: LYQ @Description:
     * 根据发送地址发送json数据到某一个url路径 @Createtime: Sep 17, 2012 @param @param url
     * 访问路径 @param @param json 传递的json @param @return 设定文件 @return String
     * 返回类型 @throws
     */
    public static String HttpClientPost(String url, String json) {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        StringBuilder result = new StringBuilder();
        try {
            StringEntity s = new StringEntity(json, "application/x-www-form-urlencoded", "UTF-8");
            s.setContentType("application/x-www-form-urlencoded");
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                Header[] headers = res.getAllHeaders();
                HttpEntity entity = res.getEntity();
                Header header = res.getFirstHeader("content-type");
                // 读取服务器返回的json数据（接受json服务器数据）
                InputStream inputStream = entity.getContent();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                BufferedReader reader = new BufferedReader(inputStreamReader);// 读字符串用的。
                String content = "";
                while (((content = reader.readLine()) != null)) {
                    result.append(content);
                }
                // 关闭输入流
                reader.close();
            }
        } catch (Exception e) {
            logger.info("HttpClientUtils:根据地址发送json数据出错:" + e.getMessage());
            e.printStackTrace();
            return null;
        }
        return result.toString();
    }

    /**
     *
     * @Title: HttpRequest @author: LYQ @Description:
     * 这里用一句话描述这个方法的作用 @Createtime: Sep 17, 2012 @param @param
     * reqUrl @param @param parameters @param @param recvEncoding @param @return
     * 设定文件 @return String 返回类型 @throws
     */
    public static String HttpRequest(String reqUrl, Map parameters, String recvEncoding, String methodType) {
        HttpURLConnection urlConnection = null;
        String responseContent = null;
        InputStream in = null;
        BufferedReader rd = null;
        try {
            StringBuffer params = new StringBuffer();
            if (parameters != null) {
                for (Iterator iter = parameters.entrySet().iterator(); iter.hasNext();) {
                    Entry element = (Entry) iter.next();
                    params.append(element.getKey().toString());
                    params.append("=");
                    params.append(URLEncoder.encode(element.getValue().toString(), HttpUtil.ENCODING));
                    params.append("&");
                }
                if (params.length() > 0) {
                    params = params.deleteCharAt(params.length() - 1);
                }
            }

            URL url = new URL(reqUrl);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod(methodType); // GET POST
            urlConnection.setConnectTimeout(HttpUtil.TIME_OUT);// （单位：毫秒）
            urlConnection.setReadTimeout(HttpUtil.READ_OUT);// （单位：毫秒）
            urlConnection.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            urlConnection.getOutputStream().write(b, 0, b.length);
            urlConnection.getOutputStream().flush();
            urlConnection.getOutputStream().close();

            in = urlConnection.getInputStream();
            rd = new BufferedReader(new InputStreamReader(in, recvEncoding));
            String tempLine = rd.readLine();
            StringBuffer temp = new StringBuffer();
            String crlf = System.getProperty("line.separator");
            while (tempLine != null) {
                temp.append(tempLine);
                temp.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = temp.toString();
            rd.close();
            in.close();
        } catch (IOException e) {
            logger.error("HttpRequest：根据地址以post或者get方式携带参数请求出错:" + e.getMessage());
            responseContent = "";
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (in != null) {
                    in.close();
                }
                if (rd != null) {
                    rd.close();
                }
            } catch (IOException e) {
                responseContent = "";
            }
        }
        return responseContent;
    }

    /**
     * @Title: HttpSend @author: LYQ @Description:
     * 通过想指定地址发送xml，并收获返回的数据。 @Createtime: Sep 17, 2012 @param @param reqUrl
     * 指定路径 @param @param xml 指定发送xml @param @return 设定文件 @return String
     * 返回类型 @throws
     */
    public static String HttpSend(String reqUrl, String xml) {
        String rel = "";
        try {
            URL my_url = new URL(reqUrl);
            URLConnection con = my_url.openConnection();
            con.setReadTimeout(HttpUtil.READ_OUT);
            con.setConnectTimeout(HttpUtil.TIME_OUT);
            con.setDoOutput(true);
            con.setRequestProperty("Pragma:", "no-cache");
            con.setRequestProperty("Cache-Control", "no-cache");
            con.setRequestProperty("Content-Type", "text/xml");
            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
            out.write(new String(xml.getBytes("ISO-8859-1")));
            out.flush();
            out.close();
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
            StringBuffer result = new StringBuffer("");
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                result.append(line);
            }
            rel = result.toString();
        } catch (Exception ex) {
            logger.error("HttpSend:发送xml到指定目录出错：" + ex.getMessage());
            return null;
        }
        return rel;
    }

    /**
     * @Title: HttpUrl @author: LYQ @Description:
     * 根据url路径求情然后获取返回值，最简单的url请求。 @Createtime: Sep 17, 2012 @param @param url
     * 请求路径 @param @param ecode 解析字符集 @param @return 设定文件 @return String
     * 返回类型 @throws
     */
    public static String HttpUrl(String url, String ecode) {
        StringBuffer ret = new StringBuffer();
        try {
            URL getUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
            InputStream in = connection.getInputStream();
            connection.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, ecode));
            String lines;
            while ((lines = reader.readLine()) != null) {
                ret.append(lines);
            }
            reader.close();
            connection.disconnect();
        } catch (Exception e) {
            logger.error("HttpUrl:根据url路径请求地址出错：" + e.getMessage());
            return null;
        }
        return ret.toString();
    }

    public static int getTIME_OUT() {
        return TIME_OUT;
    }

    public static void setTIME_OUT(int time_out) {
        TIME_OUT = time_out;
    }

    public static int getREAD_OUT() {
        return READ_OUT;
    }

    public static void setREAD_OUT(int read_out) {
        READ_OUT = read_out;
    }

    public static String getENCODING() {
        return ENCODING;
    }

    public static void setENCODING(String encoding) {
        ENCODING = encoding;
    }

    public static String requestCheckUpdateJson(String adress_Http) {
        String returnLine = "";
        try {
            URL my_url = new URL(adress_Http);
            HttpURLConnection connection = (HttpURLConnection) my_url.openConnection();
            connection.setConnectTimeout(1000 * 20);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line = "";
            while ((line = reader.readLine()) != null) {
                returnLine += line;
            }
            reader.close();
            connection.disconnect();
            System.out.println("========返回的结果的为========" + returnLine);
        } catch (Exception e) {
            returnLine = "";
            System.out.println(e.getMessage());
        }
        return returnLine;
    }


    /**
     * 发送HttpGet请求
     * @param url
     * @return
     */
    public static String sendGet(String url) {

        HttpGet httpget = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        String result = null;
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性

            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送post请求
     *
     * @param @param
     *            url
     * @param @param
     *            param
     * @return void
     * @throws @author
     *             yq
     * @date 2019年2月18日 下午5:13:41
     */
    public static String doPost(String url, String param) {
        StringBuilder sb = new StringBuilder();
        InputStream is = null;
        BufferedReader br = null;
        PrintWriter out = null;
        try {
            URL uri = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
            connection.setRequestMethod("POST");
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(10000);
            connection.setRequestProperty("accept", "*/*");
            // 发送参数
            connection.setDoOutput(true);
            out = new PrintWriter(connection.getOutputStream());
            out.print(param);
            out.flush();
            // 接收结果
            is = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line;
            // 缓冲逐行读取
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            // System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                if (is != null)
                    is.close();
                if (br != null)
                    br.close();
                if (out != null)
                    out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /**
     *
     * @Title: main @author: LYQ @Description: TODO(测试方法) @Createtime: Sep 17,
     * 2012 @param @param args 设定文件 @return void 返回类型 @throws
     */
    public static void main(String[] args) {
        // System.out.println(requestCheckUpdateJson("http://wthrcdn.etouch.cn/weather_mini?city=北京"));
        // System.out.println(requestCheckUpdateJson("http://www.weather.com.cn/data/sk/101090101.html"));
        // System.out.println(requestCheckUpdateJson("http://www.weather.com.cn/data/cityinfo/101090101.html"));
        // System.out.println(requestCheckUpdateJson("http://www.weather.com.cn/data/101090101.html"));
        // System.out.println(requestCheckUpdateJson("http://t.weather.sojson.com/api/weather/city/101090101"));
        System.out.println(requestCheckUpdateJson(
                "http://192.168.0.7:9095/sms_interface/sendmess.do?content=vbokfgewsNE=&sign=vbokfgewsNE=&mobile=15511357416"));

    }

    public static final String ORDID = "1321";

}
